<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.net.*" %>
<%@ page import="java.lang.reflect.Method" %>
<%@ page import="java.io.File" %>

<HTML>
	<HEAD>
<link href="./static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="./static/js/jquery/jquery-1.12.4.js" type="text/javascript"></script>
<script src="./static/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="./static/js/others/bootbox.min.js" type="text/javascript"></script>
<script src="./static/js/util.js" type="text/javascript"></script>
    <meta name="description" content="monitor client">
    <meta name="author" content="admin">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Pragma" content="no-cache">
    <title>e-cology流程检测</title>
    <link href="./static/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="./static/custom/css/main.css" rel="stylesheet">
    <script src="./static/bootstrap-table/bootstrap-table.js" type="text/javascript"></script>
		<style>
#mainExecute {
	margin-top: 50px;
	margin-left: 100px;
	width: 900px;
	height: auto;
}
.fixed-table-body{
    height: auto;
    overflow:hidden;
}
#leftArea {
    clear:both;
	float: left;
	padding: 15px;
	width: 1020px;
    border: #000 1px solid;
}

#buttonArea {
	float: left;
	margin-left: 10px;
	padding: 15px;
	width: 300px;
}

#resultTitle {
    margin-left: 100px;
    clear: both;
    width: 800px;
    padding: 15px;
    line-height: 25px;
    font-size: 15px;
}
#resultArea {
    margin-left: 100px;
	clear: both;
	width: 800px;
	padding: 15px;
	line-height: 25px;
	font-size: 15px;
	border: #000 1px solid;
}

.showDiv {
	min-height: 30px;
	width: 1000px;
	margin-top:10px;
	line-height: 30px;
	font-size: 15px;
	padding-left: 10px;
	cursor: pointer;
	background-color: #f1f1f1;
	/*
	border-left: 0px;
	border-top: 0px;
	border-right: #ccc 3px solid !important;
	border-bottom: #eee 3px solid !important;
	*/
}

.selectedDiv {
    /*
	border-left: #ccc 3px solid !important;
	border-top: #eee 3px solid !important;
	border-right: 0px !important;
	border-bottom: 0px !important;
	*/
	background-color: #00aaaa !important;
}

.showDiv span {
	width: 100%;
	height: 100%;
}
.errorMsg{
    margin-top:10px;
    color:red;
    font-weight:bold;
    border:#000055 1px solid;
    margin-left:20px;
}
.needcheckMsg{
    margin-top:10px;
    color:blue;
    font-weight:bold;
    border:#000055 1px solid;
    margin-left:20px;
}
.okMsg{
    margin-top:10px;
    color:green;
    font-weight:bold;
    border:#000055 1px solid;
}
.fixsuccess{
    color:green;
}
.checkOK{
    background-image : url("./static/images/ok.png");
    background-repeat:no-repeat;
    background-position:center left;
}
.fixdataBtn{
    float:right;
    line-height:22px;
}
.spanimage{
    margin-left:20px;
}
.fixmessage{
    margin-left:10px;
}
</style>
	</head>
	<body>
    <nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header" style="border-right:1px solid #dcdcdc;">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
           <span><img class="logo-less" src="./static/custom/images/logo.png"/></span>
          <a class="navbar-brand" href="#" style="color:#0f99f0;font-size:20px;">e-cology流程检测平台</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li style="margin-left:30px;" class="active"><a href="/flowtoolbar/checkMain.jsp" title="全局体检">全局体检</a></li>
            <li style="margin-left:30px;"><a href="/flowtoolbar/checkWithCondit.jsp" title="根据条件进行检测">局部数据检测</a></li>
            <li style="margin-left:30px;"><a href="/flowtoolbar/checkTools.jsp" title="常用工具">常用工具</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>
    <div class="container container-template">
      
      <div class="jumbotron body">
        <!-- 
        <h2>体检规则</h2>
         -->
        <div class="row header">
            <div class="col-md-9">
                <p id="leadTipInfo" class="lead">请检测以下内容</p>
            </div>
            <div class="col-md-3">
                <button id="examineBtn" type="button" class="btn btn-primary btn-lg">立即体检</button>
                <button id="repairBtn" type="button" class="btn btn-warning btn-lg hidden">一键修复</button>
            </div>
        </div>
         <div id="examineProgress" class="progress invisible">
          <div id="examineProgressBar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">

          </div>
        </div>
      </div>
      <div id="errorRuleList"></div>
      <table id="ruleDataTable" data-classes="table table-hover table-condensed table-no-bordered" data-row-attributes="rowAttributes" data-row-style="rowStyle">
            <colgroup>
            <col width="0">
            <col width="5%">
            <col width="30%">
            <col width="10%">
            <col width="45%">
            <col width="10%">
           </colgroup>
        <thead>
          <tr>
            <th data-field="-" data-formatter="statusFormatter" data-align="center" data-valign="middle"></th>
            <th data-field="no" data-formatter="indexFormatter" data-align="center" data-valign="middle">序号</th>
            <th data-field="ruleName" data-align="center" data-valign="middle">名称</th>
            <th data-field="examineType" data-formatter="examineTypeFormatter" data-align="center" data-valign="middle">类型</th>
            <th data-field="classDesc" data-align="center" data-valign="middle">描述</th>
            <th data-field="-" data-formatter="operationFormatter" data-align="center" data-valign="middle">操作</th>
          </tr>
        </thead>
      </table>
    </div>
<script>
<%
//设置检测列表
String resultStr = "";
//获取绝对路径
String absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
ClassLoader classLoader = new URLClassLoader(new URL[]{new File(absPath + "/classes").toURI().toURL()},Thread.currentThread().getContextClassLoader());  
Class clazz=classLoader.loadClass("checkmain.CheckExucute");//使用loadClass方法加载class,这个class是在urls参数指定的classpath下边。  

Object checkInstance = clazz.newInstance();

Method taskMethod = clazz.getMethod("getAllCheckClass",String.class,String.class);//反射
resultStr = (String)taskMethod.invoke(checkInstance,absPath,"checkDetail");  

%>
var array = <%=resultStr%>;

var showlocation = 1;
//检测或者修复数据（全部）
function checkMain(type){
    var classnames= '';
    var infoNames= '';
    if(jQuery(".showDiv").length <= 0){
        window.top.alert("没有处理内容");
        return;
    }
    //获取选中的检测类型
    var paramtotal = "";
    jQuery(".showDiv").each(function(index,ele){
        classnames += "," + jQuery(ele).find(".classname").val();
        
        infoNames += "," + jQuery(ele).find(".infoName").val();
        var paramStr = "";
        //拼接输入框
        jQuery(ele).find(".param").each(function(index1,ele1){
            if(paramStr.length > 0) paramStr += "##";
            paramStr += ele1.name + "=" + ele1.value;
        });
        if(paramtotal.length > 0) paramtotal += ";;";
        paramtotal += paramStr;
        
    });
    paramtotal = "&paramMap=" + paramtotal;
    if(classnames == ''){
        window.top.alert("请选择有效的处理内容");
        return;
    }
    if(classnames.indexOf(",") == 0){
        classnames = classnames.substring(1);
    }
    if(infoNames.indexOf(",") == 0){
        infoNames = infoNames.substring(1);
    }
    jQuery.ajax({
        url : "/flowtoolbar/checkMainAjax.jsp",
        type : "post",
        processData : false,
        data : "classnames="+classnames+"&type="+type+paramtotal,
        dataType : "json",
        complete: function(){
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
        } , 
        success : function (data, textStatus) {
            showResult(data);
        } 
    });
}
function fixDataBatch(classinfos){

    var classinfo = classinfos.shift();
    var paramtotal = "";
    paramtotal = "&paramMap=" + paramtotal;
    var escapeId = classinfo.classId;
    jQuery.ajax({
        url : "/flowtoolbar/checkMainAjax.jsp",
        type : "post",
        processData : false,
        data : "classnames="+classinfo.classname+"&type=2" + paramtotal,
        dataType : "json",
        beforeSend : function(){
            $('#leadTipInfo').html('正在进行修复: ' + classinfo.ruleName);
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            
            showRuleLoading(escapeId);
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
        } , 
        success : function(dataList){
            //console.log(data);
            data = dataList[0];
            if(data && data.result){
                //alert(data);
                //$('#periodTable').bootstrapTable('refresh');
                var examineResult = data.retList;
                if(data.result == 0){
                    showRuleOK(escapeId);
                } else {
                    //检查结果表示有问题
                    //examineResult
                    showRuleWaring(escapeId);
                    classinfo.repairDesc = data.description;
                    classinfo.canAutoRepair = data.canAutoRepair;
                    console.log(examineResult);
                    errExamineResults.push(examineResult);
                    classinfo.resultdata = examineResult;
                    errExamineRules.push(classinfo);
                }
            } else if(data.code == 302) {
                window.top.location.href = data.data;
            } else {
                alert(data.data.errMsg || data.data);
            }
        },
        complete: function(){
            count++;
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            
            if(classinfos.length>0){
                fixDataBatch(classinfos);
            } else {
                setTimeout(function(){
                    inExamine = false;
                    $('#repairBtn').removeClass('disabled');
                    hideExamineProgress();
                    if(errExamineRules.length > 0){
                        //TODO 显示修复按钮
                        $('#examineBtn').addClass('hidden');
                        $('#repairBtn').removeClass('hidden');
                        var tipinfo = [];
                        for(var j=0;j<errExamineRules.length;j++){
                            tipinfo.push(errExamineRules[j].className + '： ' + errExamineResults[j].description);
                        }
                        $('#leadTipInfo').html('共修复了'+total+'项，其中'+errExamineRules.length+'项还存在问题，请查看详情。');
                        
                    } else {
                        $('#leadTipInfo').html('共修复了'+total+'项，未发现问题.');
                    }
                    orderExaminRulesFn();
                }, 1000);
            }
        },
    });


}
//修复数据（单选）
function fixData(obj){
    //获取选中的检测类型
    var classnames = jQuery(obj).parent().parent().find("input[name='classname']").val();
    if(classnames == ''){
        window.top.alert("没有classnames");
        return;
    }
    if(classnames.indexOf(",") == 0){
        classnames = classnames.substring(1);
    }
    var paramtotal = "";
    //遍历该按钮同级的隐藏变量
    var nameList = new Array();
    jQuery(obj).parent().parent().find(".param").each(function(index,ele){
        var tempname = jQuery(ele).attr("name");
        if(nameList.indexOf(tempname) < 0 ){
            nameList.push(tempname);
        }
    });
    //拼接字符串：变量之间使用##分割，不同map之间使用;;分割
    if(jQuery(obj).parent().parent().find(".resultList").length > 0){
        paramtotal +="##";
        paramtotal += "divid=" + jQuery(obj).parent().parent().find(".resultList").attr("id");
    }
    for(var i = 0; i < nameList.length; i++){
        if(paramtotal.length > 0){
            paramtotal +="##";
        }
        var tempname = nameList[i];
        var tempvalues="";
	    jQuery(obj).parent().parent().find(".param[name='" + tempname + "']").each(function(index,ele){
	        if(tempvalues.length > 0) tempvalues +=",";
	        tempvalues += jQuery(ele).val();
	    });
        paramtotal +=tempname + "=" + tempvalues;
    }
    if(paramtotal.length > 0){
        paramtotal = "&paramMap=" + paramtotal;
    }
    var trObject = jQuery(obj).parent().parent();
    jQuery.ajax({
        url : "/flowtoolbar/checkMainAjax.jsp",
        type : "post",
        processData : false,
        data : "classnames="+classnames+"&type=2" + paramtotal,
        dataType : "json",
        beforeSend : function(){
            showDivLoading(trObject);
        },
        complete: function(){
            hideDivLoading(trObject);
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
        } , 
        success : function (data, textStatus) {
            editshowfield(data,obj);
        } 
    });
}
function toogleSelect(obj){
    jQuery(obj).toggleClass("selectedDiv");
}
function chekcAll(obj){
    
    jQuery(obj).parent().find(".fixdataCheck").each(function(index,ele){
        if(this.disabled) return;
        ele.checked = obj.checked;
    });
    

}
//根据修复结果编辑检测内容
function editshowfield(data,obj){
    for(var i = 0; i < data.length;i++){
        var objectAll = data[i];
        if(objectAll.classname && objectAll.needReload == "1"){
            var resultList = objectAll.retList;
            resultList.editHtml();
            $("#detailTable_" + objectAll.classname.substring(12)).bootstrapTable('load', resultList);
            continue;
        }
        if(window.console)console.log("objectAll",objectAll);
        if(objectAll.retList){
            for(var j = 0; j < objectAll.retList.length;j++){
                var object = objectAll.retList[j];
		        //修复成功
		        if(object.result == 0){
		            if(object.divid != null && object.divid.length > 0){
		                jQuery("#" + object.divid).parent().parent().find(".fixdataBtn").attr("disabled","disabled");
		                var message = "修复成功";
		                if(object.fixMessage){
		                    message = object.fixMessage;
		                }
		                if(jQuery("#" + object.divid).find(".fixmessage").length > 0 ){
		                    if(!jQuery("#" + object.divid).find(".fixmessage").hasClass("fixsuccess")){
		                      jQuery("#" + object.divid).find(".fixmessage").addClass("fixsuccess");
		                    }
		                    jQuery("#" + object.divid).find(".fixmessage").html(message);
		                }else{
                            jQuery("#" + object.divid).append("<span class='fixmessage fixsuccess'>" + message + "</span>");
		                }
		                jQuery(obj).parent().html("-");
		            }
		        }else{
		            if(object.divid != null && object.divid.length > 0){
                        var message = "修复失败";
                        if(object.fixMessage){
                            message = object.fixMessage;
                        }
                        if(jQuery("#" + object.divid).find(".fixmessage").length > 0 ){
                            jQuery("#" + object.divid).find(".fixmessage").html(message);
                        }else{
                            jQuery("#" + object.divid).append("<span class='fixmessage'>" + message + "</span>");
                        }
		            }
		        }
            }
        }
    }
}
//显示检测内容
var cnt = 0;
function showResult(data){
    cnt=0;
    jQuery("#resultArea").html("");
    for(var i = 0; i < data.length;i++){
        var object = data[i];
        html = showResultByAction(object);
        jQuery("#class_" + object.classname.substring(12)).remove();
        if(object.result == 0){
            if(window.console) console.log(!jQuery("#main_" + object.classname.substring(12)).hasClass("checkOK"));
	        if(!jQuery("#main_" + object.classname.substring(12)).hasClass("checkOK")) jQuery("#main_" + object.classname.substring(12)).addClass("checkOK");
	        if(jQuery("#main_" + object.classname.substring(12)).hasClass("checkNG")) jQuery("#main_" + object.classname.substring(12)).removeClass("checkNG");
	    }else{
            if(window.console) console.log(jQuery("#main_" + object.classname.substring(12)).hasClass("checkOK"));
            if(jQuery("#main_" + object.classname.substring(12)).hasClass("checkOK")) jQuery("#main_" + object.classname.substring(12)).removeClass("checkOK");
            if(!jQuery("#main_" + object.classname.substring(12)).hasClass("checkNG")) jQuery("#main_" + object.classname.substring(12)).addClass("checkNG");
	        jQuery("#main_" + object.classname.substring(12)).append(html);
        }
    }
}
function showResultByAction(object){
    
    var html = "";
    var needCheckAll = false;
    var bakdivid = "";
    //执行失败
    if(object.result == 3){
        html += "<div class='errorMsg' id='class_" + object.classname.substring(12) + "'>" + object.msg ;
    }else if(object.result == 1){
        //需要修复
        html += "<div class='needcheckMsg' id='class_" + object.classname.substring(12) + "'>" + object.msg;
    }
    //class描述
    if(object.classname){
        html+= "<input type='hidden' class='classname' value='" + object.classname + "'>";
    }
    var DetailHtml="";
    if(object.retList){
        for(var j = 0; j < object.retList.length;j++){
            var resultObj = object.retList[j];
            DetailHtml += "<div class='resultList' id='resultDetailDiv" + cnt + "'>";
            cnt++;
            if(resultObj.buttonname){
                DetailHtml+= "<input type='checkbox' class='fixdataCheck' value='" + resultObj.buttonname + "' '>";
                needCheckAll = true;
            }
            DetailHtml += "<span class='checkmessage'>" + resultObj.showMessage + "</span>";
            //遍历Object
            for(var key in resultObj) {
                //过滤公用属性： 显示信息 按钮名称 输入框列表 链接地址 连接显示名称
                if(key == "showMessage" || key == "buttonname" || key == "inputnamelist" || key == "linkurl" || key == "linkname" || key == "fixMessage"){
                    continue;
                }
                DetailHtml+= "<input type='hidden' class='param' name = '" + key + "' value='" + resultObj[key] + "'>";
            }
            if(resultObj.inputnamelist){
                var inputArray = resultObj.inputnamelist.split(",");
                for(var k =0;k< inputArray.length;k++ ){
                    var inputname = inputArray[k];
                    DetailHtml+= "<input type='text' class='param showinput' name = '" + inputname + "' value=''>";
                }
            }
            if(resultObj.buttonname){
                DetailHtml+= "<input type='button' style='display:block;' class='fixdataBtn' value='" + resultObj.buttonname + "' onclick='fixData(this)'>";
            }
            if(resultObj.linkurl && resultObj.linkname){
                DetailHtml+= "<a href=" + resultObj.linkurl +" target='_new" + cnt + "'>" + resultObj.linkname + "</a>";
            }
            DetailHtml+= "</div>";
        }
        
    }
    if(needCheckAll){
        html+= "<input type='checkbox' class='checkAll' onclick='chekcAll(this)'>";
    }
    html+= DetailHtml;
    html+= "</div>";
    return html;
}
//----------------------------------------------------------------------------------

var examineRules = <%=resultStr%>;
var orderExamineRules = [];
var inExamine = false;
function rowStyle(row, index) {
    return {
      classes: 'tr-tipinfo'
    };
}

function rowAttributes(row, index) {
    return {
      'title': row.ruleDesc,
      'id': 'tr_'+row.classId
    };
}

function statusFormatter(value, row, index) {
    var cell = ['<div class="form-group"><div class="text-center">',
                '<span class="glyphicon glyphicon-refresh glyphicon-refresh-animate status status-loading hidden"></span>',
                '<span class="glyphicon status status-ok hidden"></span>',
                '<span class="glyphicon status status-warning hidden"></span>',
                '</div></div>'];
    return cell.join('');
}

function indexFormatter(value, row, index) {
    return index + 1;
}

function examineTypeFormatter(value, row, index) {
    return value;
}

function operationFormatter(value, row, index) {
    return value;
}

function showExamineProgress(percentage){
    //$('#examineProgressBar').attr({'aria-valuenow':percentage}).css({'width':percentage+'%'}).html(percentage+'%');
    $('#examineProgress').removeClass('invisible');
}

function hideExamineProgress(){
    $('#examineProgress').addClass('invisible');
    $('#examineProgressBar').attr({'aria-valuenow':0}).css({'width':'0%'}).html('0%');
}

function showRuleLoading(classId){
    $('#tr_'+classId).attr('class', 'tr-tipinfo info');
    $('#tr_'+classId + ' .status').addClass('hidden');
    $('#tr_'+classId + ' .status.status-loading').removeClass('hidden');
}
function hideDivProgress(Obj){
    $('#examineProgress').addClass('invisible');
    $('#examineProgressBar').attr({'aria-valuenow':0}).css({'width':'0%'}).html('0%');
}

function showDivLoading(Obj){
    Obj.attr('class', 'tr-tipinfo info');
    Obj.find('.status').addClass('hidden');
    Obj.find('.status.status-loading').removeClass('hidden');
}
function hideDivLoading(Obj){
    Obj.attr('class', 'tr-tipinfo info');
    Obj.find('.status').addClass('hidden');
    Obj.find('.status.status-ok').removeClass('hidden');
}

function showRuleOK(classId){
    $('#tr_'+classId).attr('class', 'tr-tipinfo success');
    $('#tr_'+classId + ' .status').addClass('hidden');
    $('#tr_'+classId + ' .status.status-ok').removeClass('hidden');
}

function showRuleWaring(classId, repairDesc){
    $('#tr_'+classId).attr('class', 'tr-tipinfo danger');
    $('#tr_'+classId + ' .status').addClass('hidden');
    $('#tr_'+classId + ' .status.status-warning').removeClass('hidden');
    
    //TODO 删除并添加
    //if(repairDesc){
    //  $('#tr_'+classId + ' .repariDesc').addClass('hidden');
    //}
}

var count = 0;
var total = 1;
var errExamineResults = [];
var errExamineRules = [];
function examineAjaxEndLoop(rules){
    var rule = rules.shift();
    var escapeId = rule.classId.replace(/\./g, '\\.');
    var classname = rule.classname;
    var paramtotal = "&paramMap=" + paramtotal;
    $.ajax({
        type : 'POST',
        dataType : "json",
        url : '/flowtoolbar/checkMainAjax.jsp',
        data : "classnames="+classname+"&type="+0+paramtotal,
        beforeSend : function(){
            $('#leadTipInfo').html('正在进行体检: ' + rule.ruleName);
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            
            showRuleLoading(escapeId);
        },
        success : function(dataList){
            //console.log(data);
            data = dataList[0];
            if(data && data.result){
                //alert(data);
                //$('#periodTable').bootstrapTable('refresh');
                var examineResult = data.retList;
                if(data.result == 0){
                    showRuleOK(escapeId);
                } else {
                    //检查结果表示有问题
                    //examineResult
                    showRuleWaring(escapeId);
                    rule.repairDesc = data.description;
                    rule.canAutoRepair = data.canAutoRepair;
                    console.log(examineResult);
                    errExamineResults.push(examineResult);
                    rule.resultdata = examineResult;
                    errExamineRules.push(rule);
                }
            } else if(data.code == 302) {
                window.top.location.href = data.data;
            } else {
                alert(data.data.errMsg || data.data);
            }
        },
        error : function(){
            showRuleWaring(escapeId);
        },
        complete : function(xhr, textStatus){
            count++;
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            
            if(rules.length>0){
                examineAjaxEndLoop(rules);
            } else {
                setTimeout(function(){
                    inExamine = false;
                    $('#examineBtn').removeClass('disabled');
                    hideExamineProgress();
                    if(errExamineRules.length > 0){
                        //TODO 显示修复按钮
                        $('#examineBtn').addClass('hidden');
                        $('#repairBtn').removeClass('hidden');
                        var tipinfo = [];
                        for(var j=0;j<errExamineRules.length;j++){
                            tipinfo.push(errExamineRules[j].ruleName + '： ' + errExamineResults[j].description);
                        }
                        //$('#leadTipInfo').html('共检查了'+total+'项，以下'+errExamineRules.length+'项有问题，需要修复：<br>'+tipinfo.join('，'));
                        $('#leadTipInfo').html('共检查了'+total+'项，其中'+errExamineRules.length+'项有问题，需要修复.');
                        
                    } else {
                        $('#leadTipInfo').html('共检查了'+total+'项，未发现问题.');
                    }
                    orderExaminRulesFn();
                }, 1000);
            }
        }
    });
}

//排序
function orderExaminRulesFn(){
    orderExamineRules = errExamineRules.concat(examineRules);
    orderExamineRules = orderExamineRules.unique();
    $('#ruleDataTable').bootstrapTable('load', orderExamineRules);
    
}

Array.prototype.unique = function(){
 var res = [];
 var json = {};
 for(var i = 0; i < this.length; i++){
  if(!json[this[i].classId]){
   res.push(this[i]);
   json[this[i].classId] = 1;
  }
 }
 return res;
}

var errRepairResults = [];
var errRepairSuccessResults = [];
var isRepairedFlag = false;
function repairAjaxEndLoop(rules, reExamineAfterComplete){
    var rule = rules.shift();
    var escapeId = rule.classId.replace(/\./g, '\\.');
    var isNeedRestartApp = false;
    $.ajax({
        type : 'POST',
        dataType : 'json',
        url : "/flowtoolbar/checkMainAjax.jsp",
        data : "classnames="+classnames+"&type="+type+paramtotal,
        beforeSend : function(){
            $('#leadTipInfo').html('正在进行修复: ' + rule.ruleName);
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            showRuleLoading(escapeId);
        },
        success : function(dataList){
            data = dataList[0];
            //console.log(data);
            if(data && data.success){
                //alert(data);
                //$('#periodTable').bootstrapTable('refresh');
                var repairResult = data.data[0];
                if(repairResult == null){
                    //修复不成功
                    showRuleWaring(escapeId);
                } else {
                    errRepairResults.push(repairResult);
                    if(repairResult.successful){
                        //修复成功
                        errRepairSuccessResults.push(repairResult);
                        showRuleOK(escapeId);
                        //修复成功的话从errExamineRules中移除，并且重新刷新列表
                        for(var i=0;i<errExamineRules.length;i++){
                            var errRule = errExamineRules[i];
                            if(errRule.classId==rule.classId && (errRule.isNeedRestartApp==false||errRule.isNeedRestartApp=="false")){
                                errExamineRules.splice(i,1);
                                break;
                            }else if(errRule.classId==rule.classId){
                                errExamineRules[i].repairDesc = repairResult.repairDesc;
                                isNeedRestartApp = true;
                                break;
                            }
                        }
                    } else {
                        //修复不成功
                        showRuleWaring(escapeId, repairResult.repairDesc);
                    }
                }
            } else if(data.code == 302) {
                window.top.location.href = data.data;
            } else {
                alert(data.data.errMsg || data.data);
            }
            orderExaminRulesFn();
        },
        error : function(){
            showRuleWaring(escapeId);
        },
        complete : function(){
            count++;
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            
            if(rules.length>0){
                repairAjaxEndLoop(rules, reExamineAfterComplete);
            } else {
                isRepairedFlag = true;
                setTimeout(function(){
                    hideExamineProgress();
                    if(errRepairResults.length > 0){
                        //TODO 显示修复按钮
                        $('#examineBtn').removeClass('hidden');
                        $('#repairBtn').addClass('hidden');
                        //var tipinfo = [];
                        //for(var j=0;j<errRepairResults.length;j++){
                        //  tipinfo.push(errRepairResults[j].repairDesc);
                    //  }
                        //$('#leadTipInfo').html('共修复了'+total+'项，修复结果：<br>'+tipinfo.join(';<br>'));
                        var desc = '修复完成，共成功修复了'+errRepairSuccessResults.length+'项';
                        if(isNeedRestartApp){
                            desc += "，需要重启OA生效";
                        }
                        $('#leadTipInfo').html(desc);
                        errRepairSuccessResults = [];
                    }else{
                        $('#leadTipInfo').html('无法自动完成修复，请参考【查看详情】的描述进行相关操作');
                    }
                    //重新构造表
                }, 1000);
                
                if(reExamineAfterComplete){
                    /*$('#repairBtn').html('重新体检').off('click').on('click', function(){
                        window.location = '/cg/main.html?autoExamine=1';
                    });*/
                    $("#examineBtn").html('重新体检').removeClass("hidden");
                    $('#repairBtn').addClass('hidden');
                }
            }
        }
    });
}

function rollbackAjaxEndLoop(rules){
    var rule = rules.shift();
    var escapeId = rule.classId.replace(/\./g, '\\.');
    $.ajax({
        type : 'POST',
        dataType : 'json',
        contentType: "application/json; charset=utf-8",
        url : '/cp/rollback.json',
        data : JSON.stringify({ids : [rule.classId]}),
        beforeSend : function(){
            $('#leadTipInfo').html('正在进行回滚: ' + rule.ruleName);
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            showRuleLoading(escapeId);
        },
        success : function(data){
            //console.log(data);
            if(data && data.success){
                //alert(data);
                //$('#periodTable').bootstrapTable('refresh');
                var repairResult = data.data[0];
                if(repairResult == null){
                    //回滚不成功
                    //showRuleWaring(escapeId);
                } else {
                    //errRepairResults.push(repairResult);
                    if(repairResult.successful){
                        //回滚成功
                        errRepairSuccessResults.push(repairResult);
                        showRuleWaring(escapeId);
                        //回滚成功的话添加errExamineRules，并且重新刷新列表
                        rule.canRollbackCurrently = false;
                        rule.repairDesc = repairResult.repairDesc;
                        errExamineRules.push(rule);
                    } else {
                        //回滚不成功
                        //showRuleWaring(escapeId);
                    }
                }
            } else if(data.code == 302) {
                window.top.location.href = data.data;
            } else {
                alert(data.data.errMsg || data.data);
            }
            orderExaminRulesFn();
        },
        error : function(){
            showRuleWaring(escapeId);
        },
        complete : function(){
            count++;
            var percentage = Math.floor(count/total*100);
            showExamineProgress(percentage);
            
            if(rules.length>0){
                repairAjaxEndLoop(rules);
            } else {
                isRepairedFlag = true;
                setTimeout(function(){
                    hideExamineProgress();
                    //if(errRepairResults.length > 0){
                        //TODO 显示修复按钮
                        $('#examineBtn').removeClass('hidden');
                        $('#repairBtn').addClass('hidden');
                        //var tipinfo = [];
                        //for(var j=0;j<errRepairResults.length;j++){
                        //  tipinfo.push(errRepairResults[j].repairDesc);
                        //}
                        //$('#leadTipInfo').html('共修复了'+total+'项，修复结果：<br>'+tipinfo.join(';<br>'));
                        $('#leadTipInfo').html('回滚完成，共成功回滚了'+errRepairSuccessResults.length+'项');
                        errRepairSuccessResults = [];
                    //}else{
                    //  $('#leadTipInfo').html('修复完成.共成功修复了0项');
                    //}
                    //重新构造表
                }, 1000);
            }
        }
    });
}


function dateString(date){
    if(!date){
        date = new Date();
    }
    var year=date.getFullYear();     
    var month=date.getMonth()+1;     
    var day=date.getDate();     
    var hours=date.getHours();     
    var minutes=date.getMinutes();     
    var seconds=date.getSeconds();
    return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
}


function _doRepairAll(){
    count = 0;
    errRepairResults = [];
    var rules = errExamineRules.slice();
    repairAjaxEndLoop(rules, true);
}
function rowFormatter(row, index){
    return {title: row.eventMsg};
}



$(function(){
    $('#ruleDataTable').bootstrapTable({
        onRefresh: function () {
            $('#ruleDataTable').bootstrapTable('load', examineRules);
        },
        onPostBody : function(data){
            /*$('.tr-tipinfo').tooltip({
                placement: 'bottom',
                viewport: {selector: '#ruleDataTable', padding: 2}
            });*/
            //开始处理数据
            if(errExamineRules.length>0){
                $("#leadTipInfo").closest("div.header").addClass("headerException");
                $("#errorRuleList").text("以下"+errExamineRules.length+"项有问题：");
                $("#errorRuleList").show();
                var lastTr = null;
                for(var i=0;i<errExamineRules.length;i++){
                    var rule = errExamineRules[i];
                    var tr = $(document.getElementById("tr_"+rule.classId));
                    var td = tr.children(":last").eq(0);
                    td.html("");
                    var viewBtn = $("<a >查看详情</a>");
                    viewBtn.addClass("viewBtn");
                    viewBtn.data("rule", rule);
                    viewBtn.bind("click",function(){
                        var _rule = $(this).data("rule");
                        //console.log(_rule);
                        //插入一行，显示详情和修复按钮
                        var newtr = $(document.getElementById("newtr_"+_rule.classId));
                        if(newtr.length>0){
                            newtr.css("display")=="none"?newtr.show():newtr.hide();
                        }else{
                            newtr = $("<tr></tr>")
                            newtr.attr("id","newtr_"+_rule.classId).css("background-color","#fff5f5").css("line-height","24px");
                            newtr.addClass("tr-tipinfo");
                            var newtd = $("<td></td>");
                            newtd.attr("colspan",5);
                            
                            newtd.css("text-align","left");
                            newtd.html(_rule.repairDesc);
                            newtr.append("<td/>").append(newtd);
                            var newtdop = $("<td></td>");
                            newtdop.css("text-align","center");
                            var resultList = _rule.resultdata;
                            if(resultList){
                                var DetailHtml = "<table id='detailTable_" + _rule.classId + "' data-ajax='queryEvents'";
								//DetailHtml += "     data-show-columns='true' data-show-refresh='true' data-show-toggle='true' data-show-export='true' ";
								if(resultList.length > 10)DetailHtml += "    data-pagination='true' ";
								DetailHtml += "    data-row-attributes='rowFormatter' data-locale='zh-CN'>";
								DetailHtml += "    <thead>";
								DetailHtml += "        <tr>";
                                DetailHtml += "              <th data-field='-' data-formatter='statusFormatter' data-align='center' data-valign='middle'></th>";
								//DetailHtml += "            <th data-field='no' data-formatter='indexFormatter' data-align='center'>No.</th>";
								DetailHtml += "            <th data-field='showMessage' data-align='center'>描述</th>";
								DetailHtml += "            <th data-field='buttonname' style='width:90px' data-align='left' data-halign='center'>操作</th>";
								DetailHtml += "        </tr>";
								DetailHtml += "    </thead>";
								DetailHtml += "    <tbody id='detailTable_" + _rule.classId + "Body' class='nowarp-table'>";
								DetailHtml += "    </tbody>";
								DetailHtml += "</table>";
                                
                            }
                            if(_rule.canAutoRepair==true||_rule.canAutoRepair=="true"){
                                var fixBtn = $("<a href='#'>修复</a>");
                                fixBtn.bind("click",function(){
                                    repairAjaxEndLoop([_rule]);
                                });
                                newtdop.append(fixBtn);
                            }
                            newtr.append(newtdop);
                            $(this).closest("tr").after(newtr);
                            newtd.append(DetailHtml);
                            $("#detailTable_" + _rule.classId).bootstrapTable({
						        onRefresh: function () {
						            resultList.editHtml();
						            $("#detailTable_" + _rule.classId).bootstrapTable('load', resultList);
						        },
						        onPostBody : function(data){
                                        $("#detailTable_" + _rule.classId).bootstrapTable('hideLoading');
                                    }
                            }).bootstrapTable('refresh');
                        }
                    });
                    td.append(viewBtn);
                    lastTr = tr;
                }
                //插入一个正常的tr标签
                var okTr = $("<tr></tr>");
                var okTd = $("<td style='text-align:left;'></td>");
                okTd.attr("colspan",6);
                okTd.css("padding",0).css("margin","0");
                okTr.append(okTd);
                var okDiv = $("<div></div>");
                okDiv.attr("id","okRuleList")
                okDiv.html("以下"+(examineRules.length-errExamineRules.length)+"项正常：");
                okTd.append(okDiv);
                if(lastTr){
                    var newheader = $("<tr style='font-weight:bold;'><td class='faketh'></td><td class='faketh'>序号</td><td class='faketh'>名称</td><td class='faketh'>类型</td><td class='faketh'>描述</td><td class='faketh'>操作</td></tr>");
                    lastTr.after(newheader);
                    lastTr.after(okTr);
                }
            }else{
                $("#leadTipInfo").closest("div.header").removeClass("headerException");
                $("#errorRuleList").hide();
                if(isRepairedFlag){
                    var okDiv = $("div#okRuleList");
                    if(okDiv.length==0){
                        okDiv.attr("id","okRuleList");
                        $("#errorRuleList").after(okDiv);
                    }else{
                        okDiv.show();
                    }
                    okDiv.html("以下"+(examineRules.length-errExamineRules.length)+"项正常：");
                    
                }
            }
        }
    }).bootstrapTable('refresh');
    
    $('#examineBtn').off('click').on('click',function(){
        if(inExamine){
            return;
        }
        $('#examineBtn').addClass('disabled');
        inExamine = true;
        total = examineRules.length;
        if(total>0){
            count = 0;
            errExamineRules = [];
            errExamineResults = [];
            var rules = examineRules.slice();
            examineAjaxEndLoop(rules);
        }
    });
    
    $('#repairBtn').off('click').on('click',function(){
        if($('#repairBtn').hasClass("disabled")) return;
        total = errExamineRules.length;
        if(total>0){
            bootbox.confirm({
                message: "是否修复全部",
                buttons: {
                    cancel: {
                        label: '<span class="glyphicon glyphicon-remove"></span> 取消'
                    },
                    confirm: {
                        label: '<span class="glyphicon glyphicon-ok"></span> 确认'
                    }
                },
                callback: function (result) {
                    if(result){
                        var classinfos = errExamineRules.clone();
                        errExamineRules=[];
                        
                    $('#repairBtn').addClass('disabled');
                        fixDataBatch(classinfos);
                    }
                }
            });
        }
    });
    
    
});
Array.prototype.clone=function(){ return [].concat(this); }
Array.prototype.editHtml = function(){
 for(var i = 0; i < this.length; i++){
     
    var resultObj = this[i];
    var DetailHtml = "<div class='resultList'";
    if(resultObj.classname){
        DetailHtml +=" id='" + resultObj.classname.substring(12) + "_" + i + "' ";
        if(resultObj.classname.indexOf("WorkflowPlanCheck") >=0) alert(resultObj.showMessage);
    }
    DetailHtml +="><span class='checkmessage'>" + resultObj.showMessage;
    //遍历Object
    for(var key in resultObj) {
        //过滤公用属性： 显示信息 按钮名称 输入框列表 链接地址 连接显示名称
        if(key == "showMessage" || key == "buttonname" || key == "inputnamelist" || key == "linkurl" || key == "linkname" || key == "fixMessage"){
            continue;
        }
        DetailHtml+= "<input type='hidden' class='param' name = '" + key + "' value='" + resultObj[key] + "'>";
    }
    if(resultObj.inputnamelist){
        var inputArray = resultObj.inputnamelist.split(",");
        for(var k =0;k< inputArray.length;k++ ){
            var inputname = inputArray[k];
            DetailHtml+= "<input type='text' class='param showinput' name = '" + inputname + "' value=''>";
        }
    }
    if(resultObj.linkurl && resultObj.linkname){
        DetailHtml+= "<a href=" + resultObj.linkurl +" target='_new" + cnt + "'>" + resultObj.linkname + "</a>";
    }
    DetailHtml+= "</div></span>";
    this[i].showMessage = DetailHtml;
    
    if(resultObj.buttonname){
        var buttonHtml= "<a href='#' onclick='fixData(this)'>" + resultObj.buttonname + "</a>";
        this[i].buttonname = buttonHtml;
    }
 }
 return this;
}
--></script>